$(function () {
    var topicName =new Array();
    var topicValue =new Array();
    //检查时是否是分享出去的页面，添加悬浮按钮
    checkSharedPage();
   var  desc = $('#classSummary').text()
    //班级分享
    wShareFn.Focus.init({
        ele: '#c-share-btn',
        opt: checkBaseShare(shareChannel),
        title : $('#className').text(),
        lookNum : $('#studentCount').val(),
        url : window.location.href,
        desc : desc,
        img:$("#share_img").attr("src")
    });
    var obj;
    tFaceFn();
    //头像交互效果
    function tFaceFn() {
        $('.infinite-scroll').on('scroll', function () {
            var that = $(this),
                stop = that.scrollTop();
            if (stop > 20) {
                $('.bar-nav').addClass('faceSmall')
            } else {
                $('.bar-nav').removeClass('faceSmall')
            }
        })
    }

    listClassTopic(1);

    // 课程话题加载
    function listClassTopic(pageNo) {
        var joined = $('#joined').val();
        var classesId = $('#classId').val();
        var params = {"classesId":classesId,'joined':joined};
        params = JSON.stringify(params);
        loadMobilePathData({
            url: baseloaction + '/mobile/class/topic/ajax/list/topic',
            contextId: 'topic-list',
            pageNo: pageNo,
            pageCall: listClassTopic,
            params: params,
            callback: function (pageNo) {
            }
        });
    }

    $('body')
        .on('click', 'span.joinClassBtn', function () {
            joinClass();
        })
        .on('click', '#c-comment-btn', function () {
            if ($(this).hasClass('active')) {
                joinClass();
            }
        })
        .on('click', '.icon-guanbi', function () { // 移除上传的图片
            var _obj = $(this).parent();
            var fileId = _obj.data('id');
            deleteFile(fileId, function () {
                _obj.parent().remove();
                //获取初化状态的文件
                var files = obj.getFiles('inited');
                //如果队列中没有文件
                if(files.length <= 0){
                    $("#def-span-box").show();
                }
            })
        })
        .on('click', '#publish-topic-btn', function () { // 发表话题
            if (!s) {
                return;
            }
            s = false;
            //判断是否有图片上传
            var files = obj.getFiles('inited');
            if (files.length > 0) {//有文件先上传文件
                $("#tqImgWrap>span>em").remove();
                obj.upload();
            } else {//没有文件直接保存话题
                publishTopic();
            }
        })
        .on('click', '.close-popup', function () {
            $('#topic_classIds, #topicSend, #topicType, #topicTitle, #topicContext, #topic_topicType, #topic_topicImages, #topicLookPermission, #topicReplyPermission').val('');
            $("#tqImgWrap>span").remove();
            $("#tqImgWrap").append('<span id="def-span-box"><img src="' + staticPath + '/front/web/v3/img/default/default-course.gif" height="50px" width="80px"/></span>')
            $("#tqImgWrap em").each(function () {
                obj.removeFile($(this).data("id"));
            });
            obj.destroy();
        })
        .on('click', 'a.toTopicPopBtn, span.toTopicPopBtn', function () {
            initTopic();
          setTimeout(function(){
              publishTopicPopup();
          },300 );
            // 初始化图片上传
            setTimeout(function(){
                obj = uploadImgFile({
                    selectObj:'#uploadInput',
                    imgNum:4,
                    param: {'param': 'classImg'},
                    previewCallback:function (file,src) {
                        $("#tqImgWrap").append('<span><em class="wm-close-em" data-id="'+file.id+'"><i class="iconfont icon-guanbi"></i></em><img src="'+src+'" width="80px" height="50px"/></span>');
                        $("#def-span-box").hide();
                    },
                    uploadFinished:function (urlList) {
                        var imageUrls="";
                        $.each(urlList,function (index, e) {
                            if(index < urlList.length -1){
                                imageUrls+= e+",";
                            }else{
                                imageUrls+= e;
                            }
                        });
                        $("#topic_topicImages").val(imageUrls);
                        s = true;
                        //上传完成后提交数据
                        publishTopic();
                    }
                });
            },500)
        });

    // 加入班级
    function joinClass() {
        isLogin(function () {
            var classId = $('#classId').val();
            var requestUrl = $('#requestUrl').val();
            $.ajax({
                url: baseloaction + "/mobile/uc/class/user/joined",
                type:'post',
                data: {'classId': classId,
                    'requestUrl':requestUrl
                },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        if(response.message == "保存班级成员成功"){
                            var joinClassBtn = $('.joinClassBtn');
                            joinClassBtn.addClass('toTopicPopBtn');
                            joinClassBtn.removeClass('joinClassBtn');
                            joinClassBtn.text('发表话题');
                            $.toast("加入班级成功");
                        }
                    } else {
                        if (response.message == "未购买班级课程") {
                            var courseId =$('#courseId').val();
                            Zepto.confirm("亲,加入之前需要报名此班级的课程,才可加入班级哦!<br />是否要报名此课程?",function () {
                                window.location.href = baseloaction + '/mobile/course/info?courseId='+courseId+'&classFrom=1';
                            });
                            Zepto('.modal-in').find('.modal-button').text('我再想想').css('color', '#bbb');
                            Zepto('.modal-in').find('.modal-button-bold').text('立即报名').attr('style', '');
                        }else{
                            $.toast(response.message);
                        }
                    }
                }
            });
        });
    }

    // 发布话题弹窗
    function publishTopicPopup() {
        $.popup('.toTopicPopup');
    }

    // 话题类型picker
    $("#topicType").picker({
        toolbarTemplate: '<header class="bar bar-nav">\
                                  <button class="button button-link pull-left">&nbsp;</button>\
                                  <button class="button button-link pull-right close-picker">确定</button>\
                                  <h1 class="title">选择类型</h1>\
                                  </header>',
        cols: [
            {
                textAlign: 'center',    //文本居位
                values: topicName
            }
        ],
        onClose: function (o) { // picker关闭时的回调
            $('#topic_topicType').val(topicValue[topicName.indexOf(o.value[0])]);
        }
    });

    // 浏览权限picker
    $("#topicLookPermission").picker({
        toolbarTemplate: '<header class="bar bar-nav">\
                                  <button class="button button-link pull-left">&nbsp;</button>\
                                  <button class="button button-link pull-right close-picker">确定</button>\
                                  <h1 class="title">选择浏览权限</h1>\
                                  </header>',
        cols: [
            {
                textAlign: 'center',    //文本居位
                values: ['自由浏览', '登录后浏览', '仅限本班成员浏览']
            }
        ],
        onClose: function (o) { // picker关闭时的回调
            // o 当前实例对象
            var select = o.value[0];
            switch (select) {
                case '自由浏览' :
                    $('#topic_topicLookPermission').val('1');
                    break;
                case '登录后浏览' :
                    $('#topic_topicLookPermission').val('2');
                    break;
                case '仅限本班成员浏览' :
                    $('#topic_topicLookPermission').val('3');
                    break;
                default:
                    $('#topic_topicType').val('');
                    break;
            }
        }
    });

    // 回复权限picker
    $("#topicReplyPermission").picker({
        toolbarTemplate: '<header class="bar bar-nav">\
                                  <button class="button button-link pull-left">&nbsp;</button>\
                                  <button class="button button-link pull-right close-picker">确定</button>\
                                  <h1 class="title">选择评论权限</h1>\
                                  </header>',
        cols: [
            {
                textAlign: 'center',    //文本居位
                values: ['自由评论', '仅限本班成员评论']
            }
        ],
        onClose: function (o) { // picker关闭时的回调
            // o 当前实例对象
            var select = o.value[0];
            switch (select) {
                case '自由评论' :
                    $('#topic_topicReplyPermission').val('1');
                    break;
                case '仅限本班成员评论' :
                    $('#topic_topicReplyPermission').val('2');
                    break;
                default:
                    $('#topic_topicType').val('');
                    break;
            }
        }
    });

    // 发表话题
    function publishTopic() {
        var title = $('#topicTitle').val(),
            content = $('#topicContext').val(),
            topicImages = $('#topic_topicImages').val().trim(),
            classesId = $('#classId').val(),
            classify = $('#topic_topicType').val(),
            lookPermission = $('#topic_topicLookPermission').val(),
            replyPermission = $('#topic_topicReplyPermission').val();
        var params = {"title":title,"content":content,"topicImages":topicImages,"classesId":classesId,"classify":classify,"lookPermission":lookPermission,"replyPermission":replyPermission};
        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + '/mobile/uc/class/topic/ajax/publish',
            data: params,
            dataType: 'json',
            type: 'post',
            contentType: 'application/json;charset=utf-8',
            success: function (response) {
                $.toast(response.message);
                if (response.success) {
                    // 清除上次发表话题时填写的内容
                    $('#topic_classIds, #topicSend, #topicType, #topicTitle, #topicContext, #topic_topicType, #topic_topicImages').val('');
                    $("#tqImgWrap em").each(function () {
                        obj.removeFile($(this).data("id"));
                    });
                    window.location = baseloaction + '/mobile/class/topic/info?id=' + response.entity.id;
                } else {
                    $("#tqImgWrap em").show();
                }
            },
            error: function () {
                $("#tqImgWrap em").show();
                $.toast('系统繁忙，请稍候再试');
            },
            complete: function () {
                s = true;
            }
        })
    }
    var s = true;
    textInfoMore();

  function initTopic(){
      $.ajax({
          url: baseloaction + '/mobile/uc/class/topic/ajax/classesTopicTypeService',
          data:{"classId":$('#classId').val(),} ,
          dataType: 'json',
          type: 'post',
          success: function (response) {
              var list =  response.entity;
              if(list.length>0){
                  $.each(list, function (index, _m) {
                       topicName.push(_m.name);
                       topicValue.push(_m.value);
                  });
              }
          },
          error: function () {

          }
      })
  }
});

